import { login, ddLogin, getInfo, feishuLogin } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { deptList as deptListApi } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { getUserList } from '@/api/user';
import { transeToRoles } from '@/utils/permission';
import { resetRoutes } from '@/router';
import { Message } from 'element-ui';
const user = {
  state: {
    token: getToken(),
    userName: '',
    id: '',
    deptName: [],
    readAuthList: [],
    roles: [],
    authList: [],
    userInfo: {},
    userList: [],
    deptList: [],
    deptTree: [],
    postList: null,
    avatar: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, userName) => {
      state.userName = userName;
    },
    SET_DEPT: (state, deptName) => {
      state.deptName = deptName;
    },
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    CONCAT_ROLES: (state, roles) => {
      state.roles = state.roles.concat(roles);
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_USERLIST: (state, user) => {
      state.userList = user;
    },
    SET_DEPTLIST: (state, deptList) => {
      state.deptList = deptList;
    },
    SET_DEPTREE: (state, deptList) => {
      state.deptTree = deptList;
    },
    SET_POSTLIST: (state, data) => {
      state.postList = data;
    },
    SET_READAUTH: (state, data) => {
      state.readAuthList = data;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data;
          setToken(data.token);
          commit('SET_TOKEN', data.token);
          resolve(data);
        }, e => {
          reject(e);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 钉钉登录-临时码
    DingLogin({ commit }, { code }) {
      return new Promise((resolve, reject) => {
        ddLogin({ code }).then(response => {
          const { data } = response;
          commit('SET_TOKEN', data.token);
          setToken(data.token);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 飞书登录-临时码
    FeishuLogin({ commit }, params) {
      return new Promise((resolve, reject) => {
        feishuLogin(params).then(response => {
          const { data } = response;
          commit('SET_TOKEN', data.token);
          setToken(data.token);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(0, state.token).then(response => {
          const data = response.data;
          const topDeptIds = []; // 顶级部门的id列表，比如：用户部门是 研发部->产品组，那么顶级部门就是研发部
          const currentDeptIds = []; // 当前部门的所有id，比如：用户部门是 研发部->产品组，那么当前部门就是产品组
          let departmentAry = [];
          if (data.departmentAry && !Array.isArray(data.departmentAry)) {
            try {
              departmentAry = JSON.parse(data.departmentAry);
            } catch (error) { console.log(error); }
          } else if (data.departmentAry && Array.isArray(data.departmentAry)) {
            departmentAry = data.departmentAry.map(i => i.id);
          }
          if (departmentAry) {
            departmentAry.forEach(i => {
              if (i && i.length) {
                topDeptIds.push(i[0]);
                currentDeptIds.push(Number(i[i.length - 1]));
              }
            });
          }
          data.topDeptIds = topDeptIds;
          data.currentDeptIds = currentDeptIds;
          const roles = transeToRoles(data.authType);
          const authList = typeof data.authList === 'string' ? JSON.parse(data.authList) : data.authList;
          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', roles);
          } else {
            reject('未获取到用户权限！无法访问！');
          }
          if (!authList || authList.length === 0) {
            this.dispatch('LogOut');
            Message({
              type: 'error',
              message: '用户无权限登录系统，请联系管理员'
            });
            setTimeout(() => { location.href = '/'; }, 500);
            return;
          }
          commit('CONCAT_ROLES', authList);
          resetRoutes();
          // 设置是媒介还是销售

          if (authList.includes('medium:sale:orderList') && authList.includes('medium:medium:orderList')) {
            commit('SET_USER_TYPE', 3);
          } else if (authList.includes('medium:medium:orderList')) {
            commit('SET_USER_TYPE', 2);
          } else if (authList.includes('medium:sale:orderList')) {
            commit('SET_USER_TYPE', 1);
          } else {
            commit('SET_USER_TYPE', 4); // 无购物车和媒介个人中心权限
          }

          commit('SET_NAME', data.userName);
          commit('SET_DEPT', data.deptName);
          commit('SET_ID', data.id);
          commit('SET_USERINFO', data);
          commit('SET_AVATAR', data.avatar);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.token) {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          removeToken();
          resolve();
        } else {
          reject('token已清除');
        }
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        removeToken();
        resolve();
      });
    },
    // 初始化用户列表和部门列表
    initUserList({ commit, state }) {
      const userList = state.userList;
      if (userList && userList.length) return;
      const params = { page: 1, perPage: 20, userName: '' };
      getUserList(params).then(res => {
        if (res.code === 200) {
          commit('SET_USERLIST', res.data.items);
        }
      });
    },
    initDeptList({ commit, state }) {
      const deptList = state.deptList;
      if (deptList && deptList.length) return;
      deptListApi().then(res => {
        if (res.code === 200) {
          res.data.forEach(i => {
            i.name = i.value;
          });
          commit('SET_DEPTLIST', res.data);
        }
      });
    },
    initDeptTree({ commit, state }) {
      const deptTree = state.deptTree;
      if (deptTree && deptTree.length) return;
      getDepartmentAll().then(res => {
        if (res.code === 200) {
          commit('SET_DEPTREE', res.data);
        }
      });
    }
  }
};

export default user;
